package com.justrun.zjutsystem.zjutsystem.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.justrun.response.ResultCodeEnum;
import com.justrun.response.ResultEntity;
import com.justrun.utils.EncryptUtil;
import com.justrun.zjutsystem.zjutsystem.entity.AdministrativeClass;
import com.justrun.zjutsystem.zjutsystem.entity.College;
import com.justrun.zjutsystem.zjutsystem.entity.SysUser;
import com.justrun.zjutsystem.zjutsystem.entity.Teacher;
import com.justrun.zjutsystem.zjutsystem.listener.DemoDataListener;
import com.justrun.zjutsystem.zjutsystem.listener.ExcetListener;
import com.justrun.zjutsystem.zjutsystem.mapper.SysUserMapper;
import com.justrun.zjutsystem.zjutsystem.mapper.TeacherMapper;
import com.justrun.zjutsystem.zjutsystem.service.TeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.justrun.zjutsystem.zjutsystem.utils.ExcelUtil;
import com.justrun.zjutsystem.zjutsystem.vo.TeacherSelectorVo;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 教师用户信息表 服务实现类
 * </p>
 *
 * @author chandler
 * @since 2020-09-27
 */
@Slf4j
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {

    private static final String FILENAME="D:\\教师信息表.xlsx";
    private static final String SHEETNAME="教师信息";

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private SysUserMapper sysUserMapper;


    //法一
    @Override
    public ResultEntity getTeacherList(String teacherId, String teacherName, String gender, Integer pageIndex, Integer pageSize) {
        System.out.println("==========");

        Page page = new Page(pageIndex, pageSize);

        QueryWrapper wrapper = new QueryWrapper();

        if (!StringUtils.isEmpty(teacherId)) {
            wrapper.eq("teacher_id", teacherId);
        }

        if (!StringUtils.isEmpty(teacherName)) {
            wrapper.eq("teacher_name", teacherName);
        }

        if (!StringUtils.isEmpty(gender)) {
            wrapper.eq("gender", gender);
        }

        Page teacherPage = teacherMapper.selectPage(page, wrapper);
        List teacherList = teacherPage.getRecords();

        TeacherSelectorVo teacherSelectorVo = new TeacherSelectorVo();
        log.info("TeacherSelectorVo是：{}", teacherSelectorVo);
        ArrayList<TeacherSelectorVo> list = new ArrayList<>();

        wrapper.clear();
        for (int j = 0; j < teacherList.size(); j++) {
            Teacher teacher = (Teacher) teacherList.get(j);
            SysUser user = sysUserMapper.selectOne((Wrapper<SysUser>) wrapper.eq("username", teacher.getTeacherId()));
            teacherSelectorVo.setTeacherId(teacher.getTeacherId());
            teacherSelectorVo.setTeacherName(teacher.getTeacherName());
            teacherSelectorVo.setGender(teacher.getGender());
            teacherSelectorVo.setBirthday(teacher.getBirthday());
            teacherSelectorVo.setDegree(teacher.getDegree());
            teacherSelectorVo.setJobTitle(teacher.getJobTitle());
            teacherSelectorVo.setPhoneNumber(teacher.getPhoneNumber());
            teacherSelectorVo.setEmail(teacher.getEmail());
            teacherSelectorVo.setState(user.getState());
            list.add(teacherSelectorVo);
            wrapper.clear();
        }

        HashMap<String, Object> map = new HashMap<>();

        log.info("totalRecords: {}", teacherPage.getCurrent());
        log.info("currentPage {}", teacherPage.getCurrent());
        log.info("pageSize {}", teacherPage.getSize());

        map.put("totalCount", teacherPage.getTotal());
        map.put("currentPage", teacherPage.getCurrent());
        map.put("pageSize", teacherPage.getSize());
        map.put("rows", list);

        return ResultEntity.ok().data(map);

    }

//    法二
    @Override
    public ResultEntity getTeacherList2(String teacherId, String teacherName, String gender, Integer pageIndex, Integer pageSize){
        Page page = new Page(pageIndex, pageSize);
        IPage iPage = teacherMapper.findAllTeacher2(page, teacherId, teacherName, gender);
        List records = iPage.getRecords();
        HashMap<String, Object> map = new HashMap<>();
        map.put("totalCount",iPage.getTotal());
        map.put("currentPage",iPage.getCurrent());
        map.put("pageSize",iPage.getSize());
        map.put("rows",records);
        return ResultEntity.ok().data(map);
    }






    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity addTeacher(Teacher teacher) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("teacher_id", teacher.getTeacherId());
        if (teacherMapper.selectOne(wrapper) != null) {
            return ResultEntity.fail().code(ResultCodeEnum.RECORD_ALREADY_EXEST.getCode()).message(ResultCodeEnum.RECORD_ALREADY_EXEST.getMesssage());
        } else {
            teacherMapper.insert(teacher);
            String teacherId = teacher.getTeacherId();//作为默认密码
            String salt = teacherId.substring(0, 6);//截取教师编号的前6位作为密码加密的盐
            String pwdEncryed = EncryptUtil.sha256Encrypt(teacherId, salt);
            String state = "normal";//状态默认为normal
            SysUser sysUser = new SysUser();
            sysUser.setUsername(teacherId);
            sysUser.setPassword(pwdEncryed);
            sysUser.setSalt(salt);
            sysUser.setState(state);
            sysUserMapper.insert(sysUser);
            return ResultEntity.ok();
        }
    }

    @Override
    public ResultEntity batchAdd(List<List<String>> recordList) {
        return null;
    }

    @Override
    public ResultEntity turnStatus(String teacherId, String status) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",teacherId);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        log.info("user:{}",sysUser);
        sysUser.setState("ubnormal");
        queryWrapper.clear();
        queryWrapper.eq("username",teacherId);
        log.info("user:{}",sysUser);
        sysUserMapper.update(sysUser,queryWrapper);
        return ResultEntity.ok();
    }


    /**
     * 导出数据
     * @return
     */
    @Override
    public ResultEntity exportTeacher() {
        List<Teacher> teacherList = teacherMapper.selectList(null);
//        EasyExcel.write(fileName, Teacher.class).sheet("教师信息").doWrite(teacherList);
        ExcelUtil.exportTeacher(FILENAME,Teacher.class,SHEETNAME,teacherList);
        return ResultEntity.ok();
    }

    /**
     * 导入数据
     * @return
     */
    @Override
    public ResultEntity importTeacher() {
        String fileName="D:\\教师信息表.xlsx";
        ExcetListener excetListener = new ExcetListener(this);
        ExcelUtil.readExcel(fileName,excetListener,Teacher.class);
        return null;
    }


    /**
     * 导出数据
     * @param response
     * @throws Exception
     */
    /*@Override
    public void export(HttpServletResponse response) throws Exception {
        List<Teacher> teacherList = teacherMapper.selectList(null);
        ExcelUtil.writeExcel(response,teacherList,"教师信息表","sheet单1");
    }*/

    /**
     * 导入数据
     * @param teacherFile
     */
  /*  @Override
    public ResultEntity importData(MultipartFile teacherFile) {
        String fileName = teacherFile.getOriginalFilename();//获取文件名
        String fileXlsx = fileName.substring(fileName.length() - 5);//截取掉前多少个字符，获取文件的后缀名为.xlsx
        log.info("文件后缀名：{}",fileXlsx);
        String fileXls = fileName.substring(fileName.length() - 4);
        log.info("文件后缀名：{}",fileXls);
        if(!(fileXlsx.equals(".xlsx")||fileXls.equals(".xls"))){//不是excel文件
            return ResultEntity.excelFail();
        }
//        方法一
        ExcelReader excelReader=null;
        InputStream inputStream=null;
        try {
             inputStream= teacherFile.getInputStream();
            EasyExcel.read(inputStream,Teacher.class,new)
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/


}
